package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class TrackReceiver {
    @Autowired
    private TrackInfoService trackInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK),
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = "true",autoDelete = "false"),
            key = {MqConst.ROUTING_TRACK_STAT_UPDATE}
    ))
    public void updateStat(String msg, Message message, Channel channel) {
//        判断当前数据msg是否为空（是否需要更新）：
        if (!StringUtils.isEmpty(msg)){
//            查询专辑的数据类型：
            TrackStatMqVo trackStatMqVo = JSON.parseObject(msg, TrackStatMqVo.class);
//            获取交易编号，防止消息重复消费：
            String businessNo = trackStatMqVo.getBusinessNo();
//            执行成功，说明是第一次消费：
            Boolean result = this.redisTemplate.opsForValue().setIfAbsent(businessNo, "1", 10, TimeUnit.MINUTES);
            if (result){
                try {
                    trackInfoService.updateTrackStat(trackStatMqVo);
                } catch (Exception e) {
//                    如果有异常，在异常中删除上一个key：
                    this.redisTemplate.delete(businessNo);
                    log.error(e.getMessage(),e);
                }
            }
        }

//        3.手动应答
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
